<template>
  <view class="user-container">
    <!-- 顶部背景及用户信息 -->
    <view class="user-header">
      <view class="header-actions">
        <view class="id-number">ID: {{userInfo.idCard}}</view>
      </view>
      <view class="user-info">
        <view class="avatar-container">
          <image v-if="userInfo.avatar" class="avatar-image" @click="updateAvatar" :src="userInfo.avatar" mode="aspectFill"></image>
          <text v-else class="avatar-text" @click="updateAvatar">{{userInfo.username ? userInfo.username.substring(0, 1) : '用'}}</text>
        </view>
        <view class="user-detail">
          <view class="username">{{userInfo.username || '用户'}}</view>
          <view class="user-meta">
            <view class="account-id">账号：{{userInfo.id || ''}}</view>
            <view class="verified-tag" v-if="userInfo.auth === 1">
              <u-icon name="checkmark-circle" size="14" color="#fff"></u-icon>
              <text>已认证</text>
            </view>
            <view class="unverified-tag" v-else @click="goToVerification">
              <u-icon name="info-circle" size="14" color="#fff"></u-icon>
              <text>未认证</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 功能列表 -->
    <view class="menu-section">
      <view class="menu-list">
        <!-- <view class="menu-item" @click="navigateTo('contract')">
          <view class="menu-left">
            <u-icon name="file-text" size="20" color="#2468f2"></u-icon>
            <text class="menu-label">合同管理</text>
          </view>
          <view class="menu-right">
            <switch class="menu-switch" color="#2468f2"></switch>
          </view>
        </view> -->

        <view class="menu-item" @click="navigateTo('password')">
          <view class="menu-left">
            <u-icon name="lock" size="20" color="#2468f2"></u-icon>
            <text class="menu-label">修改交易密码</text>
          </view>
          <view class="menu-right">
            <u-icon name="arrow-right" size="16" color="#ccc"></u-icon>
          </view>
        </view>

        <view class="menu-item" @click="navigateTo('account')">
          <view class="menu-left">
            <u-icon name="trash" size="20" color="#2468f2"></u-icon>
            <text class="menu-label">注销账号</text>
          </view>
          <view class="menu-right">
            <u-icon name="arrow-right" size="16" color="#ccc"></u-icon>
          </view>
        </view>

        <view class="menu-item" @click="handleLogout">
          <view class="menu-left">
            <u-icon name="arrow-right" size="20" color="#2468f2"></u-icon>
            <text class="menu-label">退出登录</text>
          </view>
          <view class="menu-right">
            <u-icon name="arrow-right" size="16" color="#ccc"></u-icon>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import {apiConfig} from '@/utils/apiConfig'
import { getAccessToken } from '@/utils/auth'
import { updateUserAvatar } from '@/api/user'
export default {
  data() {
    return {
      loading: false
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  onShow() {
    // 每次显示页面时获取最新的用户信息
    this.getUserInfo()
  },
  onLoad() {
    // 禁止页面滚动
    uni.setPageMeta({
      scrollTop: 0,
      overflow: 'hidden'
    });

    // 首次加载时获取用户信息
    this.getUserInfo()
  },
  methods: {
    ...mapActions(['GetUserInfo', 'LogOut']),

    // 获取用户信息
    getUserInfo() {
      if (this.loading) return;

      this.loading = true;
      uni.showLoading({
        title: '加载中...',
        mask: true
      });

      this.GetUserInfo().then(() => {
        this.loading = false;
        uni.hideLoading();
      }).catch(error => {
        this.loading = false;
        uni.hideLoading();
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
        console.error('获取用户信息失败:', error);
      });
    },

    // 跳转到实名认证页面
    goToVerification() {
      uni.navigateTo({
        url: '/pages/user/verification/index'
      });
    },
    updateAvatar() {
      console.log('updateAvatar')
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          const files = res.tempFiles[0]
          // 上传图片到服务器
          this.uploadImage(tempFilePath);
        }
      });
    },
    uploadImage(filePath) {
      if (this.uploading) {
        return uni.showToast({
          title: '正在上传中，请稍候',
          icon: 'none'
        });
      }

      this.uploading = true;
      uni.showLoading({
        title: '上传中...'
      });

      uni.uploadFile({
        timeout: 10000,
        url: apiConfig.baseUrl + '/app-api/infra/file/upload',
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': 'Bearer ' + getAccessToken(),
          'tenant-id': apiConfig.tenantId
        },
        method: 'post',
        success: (uploadRes) => {
          console.log(uploadRes);
          try {
            const data = JSON.parse(uploadRes.data);
            console.log(data)
            console.log(data.data)
            console.log(data.data.url)
            if (data.code === 0 && data.data) {

              updateUserAvatar({
                avatar: data.data
              }).then(res => {
                this.userInfo.avatar = data.data
                uni.showToast({
                  title: '上传成功',
                  icon: 'success'
                });
                this.uploading = false;
                uni.hideLoading();
              })
            } else {
              uni.showToast({
                title: data.msg || '上传失败',
                icon: 'none'
              });
            }
          } catch (e) {
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          });
          this.uploading = false;
          uni.hideLoading();
        }
      })
    },
    navigateTo(page) {
      // 页面跳转
      if (page === 'password') {
        uni.navigateTo({
          url: '/pages/user/password/index'
        });
      } else if (page === 'account') {
        uni.navigateTo({
          url: '/pages/user/account/index'
        });
      } else if (page === 'contract') {
        uni.switchTab({
          url: '/pages/contract/index'
        });
      }
    },

    handleLogout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 调用退出登录接口
            this.LogOut().then(() => {
              uni.showToast({
                title: '已退出登录',
                icon: 'success'
              });

              // 退出登录后跳转到登录页
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/login/index'
                });
              }, 1500);
            }).catch(() => {
              uni.showToast({
                title: '退出登录失败',
                icon: 'none'
              });
            });
          }
        }
      });
    }
  }
}
</script>

<style lang="scss">
.user-container {
  height: 100vh;
  background-color: #f7f7f7;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

/* 顶部用户信息区域 */
.user-header {
  height: 240rpx;
  position: relative;
  background-color: #1989fa;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(25, 137, 250, 0.2);
}

.header-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 10rpx;
}

.id-number {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
  background-color: rgba(255, 255, 255, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.user-info {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}

.avatar-container {
  width: 120rpx;
  height: 120rpx;
  background-color: #fff;
  border-radius: 12rpx;
  margin-right: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid rgba(255, 255, 255, 0.8);
  overflow: hidden;
}

.avatar-image {
  width: 100%;
  height: 100%;
}

.avatar-text {
  color: #ff4b4b;
  font-size: 46rpx;
  font-weight: 600;
}

.user-detail {
  flex: 1;
  color: #fff;
}

.username {
  font-size: 40rpx;
  font-weight: 600;
  margin-bottom: 16rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.user-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.account-id {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
  margin-right: 20rpx;
}

.verified-tag {
  display: flex;
  align-items: center;
  font-size: 22rpx;
  color: #fff;
  background-color: rgba(76, 217, 100, 0.3);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.unverified-tag {
  display: flex;
  align-items: center;
  font-size: 22rpx;
  color: #fff;
  background-color: rgba(255, 69, 58, 0.3);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.verified-tag text, .unverified-tag text {
  margin-left: 4rpx;
}

/* 菜单列表 */
.menu-section {
  padding-top: 20rpx;
  height: calc(100% - 240rpx);
  overflow: hidden;
}

.menu-list {
  margin: 0 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f5f5f5;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-left {
  display: flex;
  align-items: center;
}

.menu-label {
  font-size: 28rpx;
  color: #333;
  margin-left: 16rpx;
}

.menu-right {
  display: flex;
  align-items: center;
}

.menu-switch {
  transform: scale(0.8);
}
</style>
